#include "../Comm/Comm.h"
#include "../ObjectPool/ObjectPool.h"
#include "../PageCache/PageMap.h"
#include "../Comm/Comm.h"
#include <cassert>

struct PageInfo {
    void* span_ptr;      // 指向Span结构
    size_t size_class;   // 大小分类
    bool is_allocated;   // 是否已分配
    
    PageInfo() : span_ptr(nullptr), size_class(0), is_allocated(false) {}
};

void TestPageMap() {
    std::cout << "Testing PageMap for 64-bit system...\n\n";
    
    TCMalloc_PageMap3<51> page_map;
    PageInfo info1;
    info1.span_ptr = reinterpret_cast<void*>(0x12345678);
    info1.size_class = 5;
    info1.is_allocated = true;
    
    // 测试1: 基本的设置和获取
    std::cout << "Test 1: Basic Set/Get\n";
    void* addr1 = SystemAlloc(1);
    unsigned long long page_id1 = (unsigned long long)addr1 >> 13;
    
    assert(page_map.set((unsigned long long)addr1 >> 13, &info1));
    PageInfo* retrieved = (PageInfo*)page_map.get(page_id1);
    assert(retrieved != nullptr);
    assert(retrieved->span_ptr == info1.span_ptr);
    assert(retrieved->size_class == 5);
    assert(retrieved->is_allocated == true);
    std::cout << "  ✓ Basic operations passed\n\n";
    
    // 测试2: 稀疏地址空间
    std::cout << "Test 2: Sparse Address Space\n";
    void* addr2 = SystemAlloc(1);
    void* addr3 = SystemAlloc(1);
    void* addr4 = SystemAlloc(1);
    void* addr5 = SystemAlloc(1);
    void* addrs[] = {
        addr2,addr3,addr4,addr5
    };
    
    for (int i = 0; i < 4; i++) {
        PageInfo* info = new PageInfo;
        info->size_class = i + 1;
        info->is_allocated = true;
        assert(page_map.set((unsigned long long)addrs[i] >> 13, info));
    }
    
    for (int i = 0; i < 4; i++) {
        PageInfo* info = (PageInfo*)page_map.get((unsigned long long)addrs[i] >> 13);
        assert(info != nullptr);
        assert(info->size_class == static_cast<size_t>(i + 1));
    }
    std::cout << "  ✓ Sparse addresses handled correctly\n\n";
    
    // 测试3: 不存在的地址
    std::cout << "Test 3: Non-existent Address\n";
    void* non_existent = reinterpret_cast<void*>(0x8888888888888000ULL);
    assert(page_map.get((unsigned long long)non_existent >> 13) == nullptr);
    std::cout << "  ✓ Returns nullptr for unmapped address\n\n";
        
    // 测试4: 内存使用统计
    std::cout << "Test 5: Memory Statistics\n";
    page_map.PrintStats();
    
    std::cout << "\n✅ All tests passed!\n";
}

int main()
{
	TestPageMap();
	return 0;
}